package com.itheima.controller;

import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/getUsername")
    public Result getUsername(){
        //登录完成后，从框架提供的上下文对象中获取用户信息
        try {
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (user !=null){
                String username = user.getUsername();
                return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,username);
            }else {
                return new Result(false,MessageConstant.GET_USERNAME_FAIL);
            }
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_USERNAME_FAIL);
        }
    }
}
